package com.sysd.imgboard.service.user;

import java.util.ArrayList;
import java.util.List;

import org.slim3.datastore.Datastore;

import com.sysd.imgboard.constant.AppConst;
import com.sysd.imgboard.meta.ChildMeta;
import com.sysd.imgboard.meta.ImageMeta;
import com.sysd.imgboard.model.Child;
import com.sysd.imgboard.model.Image;
import com.sysd.imgboard.model.Thread;


public class IndexService {

    /**
     * 指定のoffsetからlimitまでのスレッドを取得する
     * @param offset
     * @param limit
     * @return
     */
    public List<Thread> getThreads(Integer offset, Integer limit){
        
        ChildMeta cm = new ChildMeta();
        ImageMeta im = new ImageMeta();
        
        List<Thread> threads = new ArrayList<Thread>();
        
        List<Child> list = Datastore.query(cm)
            .offset(offset)
            .limit(limit)
            .filter(cm.childId.equal(1L))
            .sort(cm.threadId.asc)
            .asList();
        
        for(Child data : list){

            int children_num = Datastore.query(cm)
                .filter(cm.threadId.equal(data.getThreadId()))
                .countQuickly();
            int children_start = children_num - AppConst.DEFAULT_CHILD_VIEW_NUMBER();
            if(children_start < 0){
                children_start = 0;
            }
            
            List<Child> children = Datastore.query(cm)
                .filter(cm.threadId.equal(data.getThreadId()))
                .offset(children_start)
                .sort(cm.childId.asc)
                .asList();
            
            for(Child child : children){
                List<Image> il = Datastore.query(im).filter(
                    im.threadId.equal(child.getThreadId()),
                    im.childId.equal(child.getChildId())
                    ).asList();
                if(il != null && il.size() == 1){
                    child.setImageData(il.get(0).getSmall());
                }
            }
            

            
            Thread th = new Thread();
            th.setThreadId(data.getThreadId());
            th.setChildren(children);
            threads.add(th);
        }
        
        return threads;
    }
}
